import { configuration } from '../../env.product.js'

import axios from 'axios'

/**
 * 请求项目数据的请求体
 */
async function http({ url, method = 'GET', param = {} }) {
	let httpUrl = configuration.url + url;
	if (method === 'GET') {
		const queryParams = jsonToGetParams(param);
		httpUrl += queryParams;
	}
	try {
		const response = await axios({
			url: httpUrl,
			method,
			data: method === 'GET' ? {} : param,
			headers: {
				'content-type': 'application/json',
				// 'Authorization': localStorage.getItem('token') || ''
				'Token': localStorage.getItem('token') || ''
			}
		});
		return response.data;
	} catch (error) {
		throw error;
	}
}

 function ask(e) {
	return http({
		url: e[0],
		method: e[1],
		param: e[2]
	})
}
export { ask }

/**
 * 获取高德信息请求体
 * @param type
 * @param method
 * @param re
 * @returns {Promise<any>}
 */

async function pubulicHttp({ url, method, params }) {
	let requestUrl = ''
	switch (method) {
		case 'GET':
			requestUrl = configuration.gaodeUrl + url + jsonToGetParams(params)
			break
		case 'POST':
			requestUrl = configuration.gaodeUrl + url
	}
	const { data } = await axios({
		url: requestUrl,
		method: method,
		data: method === 'GET' ? {} : params,
		headers: { 'Content-Type': 'application/json;charset=UTF-8' }
	})
	return data
}
async function gdAsk(e) {
	console.log(e)
	return pubulicHttp({
		url: e[0],
		method: e[1],
		params: e[2]
	})
}
export { gdAsk }

/**
 * GET参数转字符串
 * @param jsonObj
 * @returns {string}
 */
function jsonToGetParams(jsonObj) {
	const params = Object.entries(jsonObj)
		.map(([key, value]) => `${key}=${value}`)
		.join('&')
	if (params.length >= 1) {
		return '?' + params
	} else {
		return params
	}
}
